package siau.android.base

import android.content.Context
import android.util.TypedValue
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import hhm.android.library.utils.GetIntListener
import hhm.android.library.utils.OnMultiClickListener
import siau.android.http.model.FamilyListResponse
import siau.android.http.model.FamilyModel

class BottomSingleFamilySelectSheet : BottomSheetDialog {

    private var listener: GetIntListener
    lateinit var adapter: BottomSingleFamilySelectAdapter

    constructor(context: Context, familyListResponse: FamilyListResponse, listener: GetIntListener) : super(context) {
        createView(familyListResponse)
        this.listener = listener
    }

    private fun createView(familyListResponse: FamilyListResponse) {
        val bottomSheetView: View = layoutInflater.inflate(R.layout.item_bottom_select_family_item, null)
        setContentView(bottomSheetView)

        val recycler = bottomSheetView as RecyclerView
        recycler.layoutManager = LinearLayoutManager(context)
        val list = ArrayList<FamilyModel>()
        familyListResponse.families.forEach {
            list.add(it)
        }
        adapter = BottomSingleFamilySelectAdapter(context, familyListResponse.defaultFamilyId, list, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                val pos = v?.tag as Int
                listener.getInt(list[pos].familyId)
                dismiss()
            }
        })
        recycler.adapter = adapter

        // 注意：这里要给layout的parent设置peekHeight，而不是在layout里给layout本身设置，下面设置背景色同理，坑爹！！！
        val bottomSheetBehavior: BottomSheetBehavior<*> = BottomSheetBehavior.from(
            bottomSheetView.parent as View
        )
//        bottomSheetView.measure(0,0)
//        behavior.peekHeight = bottomSheetView.measuredHeight

//        bottomSheetBehavior.peekHeight = dp2px(235f)
        //允许点击外部关闭，不允许滑动关闭
        bottomSheetBehavior.isHideable = false
        (bottomSheetView.parent as View).setBackgroundColor(context.resources.getColor(R.color.trans))
    }

    fun dp2px(dpValue: Float?): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, dpValue!!, context.resources.displayMetrics
        ).toInt()
    }

    override fun dismiss() {
        super.dismiss()
        SBApplication.startShowChangeFamilySheet = false
    }
}